#include "ringbuffer.h"

ringbuff_t ringBuff={0};

void ringBuff_Init(uint16_t buf_size)
{
    /*init write and read index*/
    ringBuff.read_index = 0;
    ringBuff.write_index = 0;
    ringBuff.buff_size = buf_size;
}

buff_state_e ringBuff_Empty(void)
{
    buff_state_e status = Buff_NORMAL;
    /*ringBuff is empty ???*/
    if (ringBuff.read_index == ringBuff.write_index)
    {
        status = Buff_EMPTY;

#if ringBuffDebug == 1
        printf("ringBuff is empty \r\n");
#endif
    }
    return status;
}

buff_state_e ringBuff_Full(void)
{
    buff_state_e status = Buff_NORMAL;
    /*ringBuff is full ???*/
    if (((ringBuff.write_index + 1) % ringBuff.buff_size) == ringBuff.read_index)
    {
        status = Buff_FULL;
#if ringBuffDebug == 1
        printf("ringBuff is full \r\n");
#endif
    }
    return status;
}

/*
 * length : write data length
 * prt    : buffer prt
 */
uint16_t ringBuff_Write(uint8_t *ptr, uint16_t length)
{
    buff_state_e status = Buff_NORMAL;
    /*get ringBuff status */
    status = ringBuff_Full();

    if (status == Buff_FULL)
    {
        return 0;
    }
    else
    {
        /*copy ptr data into ringBuff */
        memcpy(&ringBuff.buff_ptr[ringBuff.write_index], ptr, length);

        /*write index cnt*/
        ringBuff.write_index = (ringBuff.write_index + 1) % ringBuff.buff_size;

        /*return write index val*/
        return ringBuff.write_index;
    }
    return 0;
}

/*
 * length : read data length
 * prt    : buffer prt
 */
uint16_t ringBuff_Read(uint8_t *ptr, uint16_t length)
{
    buff_state_e status = Buff_NORMAL;
    /*get ringBuff status */
    status = ringBuff_Empty();

    if (status == Buff_EMPTY)
    {
        return 0;
    }
    else
    {
        /*copy ringBuff data to ptr*/
        memcpy(ptr, &ringBuff.buff_ptr[ringBuff.read_index], length);
#if ringBuffDebug ==1
        for (uint8_t i = 0; i < length; i++)
        {
            printf("readdata=%d,\r\n", ptr[i]);
        }
#endif
        /*read index cnt*/
        ringBuff.read_index = (ringBuff.read_index + 1) % ringBuff.buff_size;

        /*return read index*/
        return ringBuff.read_index;
    }
    return 0;
}
